<script setup lang="ts">
  import { ref, computed, watch } from 'vue';
  import { useLowcodeStore } from '@/store/features/lowcode';
  import { storeToRefs } from 'pinia';
  import type { ComponentInstance } from '@/types/lowcode';

  const lowcodeStore = useLowcodeStore();
  const { canvasComponents, selectedComponentId } = storeToRefs(lowcodeStore);

  // 获取组件列表
  const getCanvasComponents = computed<ComponentInstance[]>(() => canvasComponents.value);
  // 获取选中的组件Id
  const getSelectedComponentId = computed(() => selectedComponentId.value);
  const selectedComponent = ref<ComponentInstance | null>(null);
  // 监听选中组件变化
  watch(
    getSelectedComponentId,
    (id) => {
      if (id) {
        const findCanvasComponent = getCanvasComponents.value.find((item) => item.id === id);
        if (findCanvasComponent) {
          selectedComponent.value = findCanvasComponent;
        } else {
          selectedComponent.value = null;
        }
      } else {
        selectedComponent.value = null;
      }
    },
    { immediate: true },
  );

  const handlePropChange = () => {
    if (selectedComponent.value) {
      lowcodeStore.updateComponentInstance(selectedComponent.value);
    }
  };
  const handlePositionChange = () => {
    if (selectedComponent.value) {
      lowcodeStore.updateComponentInstance(selectedComponent.value);
    }
  };
</script>
<template>
  <div class="component-config">
    <div v-if="!selectedComponent" class="empty-config">请选择一个组件进行配置</div>
    <div v-else class="config-item">
      <h3>组件配置</h3>
      <div class="form-item">
        <label>组件ID</label>
        <input type="text" v-model="selectedComponent.id" :disabled="true" />
      </div>
      <!-- 动态渲染属性配置 -->
      <template v-for="(_value, key) in selectedComponent.props" :key="key">
        <div class="form-item">
          <label></label>
          <input type="text" v-model="selectedComponent.props[key]" @input="handlePropChange" />
        </div>
      </template>
      <!-- 位置大小配置 -->
      <div class="form-item">
        <label>位置 Y</label>
        <input type="number" v-model="selectedComponent.y" @input="handlePositionChange" />
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  .component-config {
    width: 300px;
    height: 100%;
    border-left: 1px solid #e5e7eb;
    padding: 16px;
    background-color: white;
    overflow-y: auto;
    .empty-config {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
    }
    .config-item {
      .form-item {
        margin-bottom: 16px;
        label {
          display: block;
          margin-bottom: 4px;
          font-weight: 500;
        }
        input {
          width: 100%;
          padding: 8px;
          border: 1px solid #ddd;
          border-radius: 4px;
        }
      }
    }
  }
</style>
